<template>
  <div class="browse-history">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="浏览记录"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <div class="content">
      <van-empty v-if="loading" description="加载中...">
        <template #image>
          <van-loading type="spinner" size="36" />
        </template>
      </van-empty>

      <van-empty
        v-else-if="historyList.length === 0"
        description="暂无浏览记录"
      />

      <template v-else>
        <!-- 操作按钮 -->
        <div class="actions">
          <van-button
            icon="delete-o"
            size="small"
            type="danger"
            plain
            @click="handleClearAll"
          >
            清空记录
          </van-button>
        </div>

        <!-- 浏览记录列表 -->
        <div class="history-list">
          <van-cell-group
            inset
            v-for="(group, date) in groupedHistoryList"
            :key="date"
            :title="formatDate(date)"
          >
            <van-swipe-cell
              v-for="item in group"
              :key="item.id"
              :before-close="beforeClose"
            >
              <van-cell @click="navigateToDetail(item)" :border="false">
                <template #icon>
                  <van-image
                    width="40"
                    height="40"
                    fit="cover"
                    :src="item.image || 'https://img.yzcdn.cn/vant/cat.jpeg'"
                    style="margin-right: 10px; border-radius: 4px"
                  />
                </template>
                <template #title>
                  <div class="item-title">
                    <span>{{ item.name || "未知项目" }}</span>
                    <span class="time">{{ formatTime(item.viewTime) }}</span>
                  </div>
                </template>
                <template #label>
                  <div class="item-type">{{ getItemTypeName(item.type) }}</div>
                  <div class="view-duration">
                    浏览时长: {{ formatDuration(item.duration) }}
                  </div>
                </template>
              </van-cell>

              <template #right>
                <van-button
                  square
                  type="danger"
                  text="删除"
                  class="delete-button"
                  @click="handleDelete(item.id)"
                />
              </template>
            </van-swipe-cell>
          </van-cell-group>
        </div>

        <!-- 加载更多 -->
        <div class="load-more" v-if="hasMore">
          <van-button plain type="primary" size="small" @click="loadMore"
            >加载更多</van-button
          >
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { showToast, showConfirmDialog } from "vant";
import { useUserStore } from "../../stores/userStore";
import {
  getBrowseHistoryPage,
  deleteBrowseHistory,
  clearBrowseHistory,
} from "../../api/user";

const router = useRouter();
const userStore = useUserStore();

// 状态变量
const loading = ref(true);
const historyList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);

// 获取用户ID
const userId = computed(() => userStore.userId);

// 格式化日期
const formatDate = (dateStr) => {
  const date = new Date(dateStr);
  const today = new Date();
  const yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);

  if (date.toDateString() === today.toDateString()) {
    return "今天";
  } else if (date.toDateString() === yesterday.toDateString()) {
    return "昨天";
  } else {
    return `${date.getMonth() + 1}月${date.getDate()}日`;
  }
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return "";
  const date = new Date(timestamp);
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  return `${hours}:${minutes}`;
};

// 格式化浏览时长
const formatDuration = (seconds) => {
  if (!seconds) return "0秒";
  if (seconds < 60) return `${seconds}秒`;
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return remainingSeconds > 0
    ? `${minutes}分${remainingSeconds}秒`
    : `${minutes}分钟`;
};

// 获取项目类型名称
const getItemTypeName = (type) => {
  switch (type) {
    case "recipe":
      return "食谱";
    case "food":
      return "食材";
    default:
      return "未知类型";
  }
};

// 按日期分组
const groupedHistoryList = computed(() => {
  const groups = {};

  historyList.value.forEach((item) => {
    const date = new Date(item.viewTime || Date.now()).toDateString();
    if (!groups[date]) {
      groups[date] = [];
    }
    groups[date].push(item);
  });

  return groups;
});

// 加载浏览记录
const loadBrowseHistory = async (refresh = false) => {
  if (refresh) {
    currentPage.value = 1;
    historyList.value = [];
    hasMore.value = true;
  }

  if (!hasMore.value) return;

  try {
    loading.value = true;
    const res = await getBrowseHistoryPage(
      userId.value,
      currentPage.value,
      pageSize.value
    );

    if (res.code === 200 && res.data) {
      if (res.data.records && res.data.records.length > 0) {
        historyList.value.push(...res.data.records);
        currentPage.value++;

        // 检查是否还有更多数据
        hasMore.value = historyList.value.length < res.data.total;
      } else {
        hasMore.value = false;
      }
    } else {
      showToast("获取浏览记录失败");
      hasMore.value = false;
    }
  } catch (error) {
    console.error("加载浏览记录失败", error);
    showToast("获取浏览记录失败");
  } finally {
    loading.value = false;
  }
};

// 加载更多
const loadMore = () => {
  loadBrowseHistory();
};

// 删除记录
const handleDelete = async (id) => {
  try {
    const res = await deleteBrowseHistory(id, userId.value);
    if (res.code === 200) {
      showToast("删除成功");
      historyList.value = historyList.value.filter((item) => item.id !== id);
    } else {
      showToast("删除失败");
    }
  } catch (error) {
    console.error("删除浏览记录失败", error);
    showToast("删除失败");
  }
};

// 清空所有记录
const handleClearAll = () => {
  showConfirmDialog({
    title: "确认清空",
    message: "确定要清空所有浏览记录吗？",
  })
    .then(async () => {
      try {
        const res = await clearBrowseHistory(userId.value);
        if (res.code === 200) {
          showToast("清空成功");
          historyList.value = [];
        } else {
          showToast("清空失败");
        }
      } catch (error) {
        console.error("清空浏览记录失败", error);
        showToast("清空失败");
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 滑动单元格关闭前的回调函数
const beforeClose = ({ position, instance }) => {
  switch (position) {
    case "right":
      instance.close();
      break;
  }
};

// 导航到详情页
const navigateToDetail = (item) => {
  if (!item.type || !item.targetId) return;

  switch (item.type) {
    case "recipe":
      router.push(`/recipe/${item.targetId}`);
      break;
    case "food":
      router.push(`/food/${item.targetId}`);
      break;
    default:
      break;
  }
};

onMounted(() => {
  loadBrowseHistory(true);
});
</script>

<style scoped>
.browse-history {
  padding-top: 46px;
  min-height: 100vh;
  background-color: #f7f8fa;
}

.content {
  padding: 16px;
}

.actions {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 12px;
}

.item-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.time {
  font-size: 12px;
  color: #969799;
}

.item-type {
  font-size: 12px;
  color: #969799;
  background-color: #f2f3f5;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
  margin-top: 4px;
}

.view-duration {
  font-size: 12px;
  color: #969799;
  margin-top: 4px;
}

.delete-button {
  height: 100%;
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

.history-list {
  margin-bottom: 20px;
}
</style>
